﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AerolineaApp.Models;

namespace AerolineaApp.Controllers
{ 
    public class AvionController : Controller
    {
        private AerolineaBD db = new AerolineaBD();

        public ViewResult Index()
        {
            return View();
        }

        public ViewResult ListaAviones()
        {
            var aviones = db.Aviones.Include(a => a.Aerolinea);
            return View(aviones.ToList());
        }

        public ViewResult Details(int id)
        {
            Avion avion = db.Aviones.Find(id);
            return View(avion);
        }

        public ActionResult Create()
        {
            ViewBag.AerolineaId = new SelectList(db.Aerolineas, "Id", "Nombre");
            return View();
        } 

        [HttpPost]
        public ActionResult Create(Avion avion)
        {
            if (ModelState.IsValid)
            {
                Aerolinea aerolinea = (from a in db.Aerolineas
                                       where a.Id == avion.AerolineaId
                                       select a).Single();

                aerolinea.Cantidad_Aviones += 1;
                avion.Dia = DateTime.Today;
                db.Aviones.Add(avion);

                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            ViewBag.AerolineaId = new SelectList(db.Aerolineas, "Id", "Nombre", avion.AerolineaId);
            return View(avion);
        }
        
        public ActionResult Edit(int id)
        {
            Avion avion = db.Aviones.Find(id);
            ViewBag.AerolineaId = new SelectList(db.Aerolineas, "Id", "Nombre", avion.AerolineaId);
            return View(avion);
        }

        [HttpPost]
        public ActionResult Edit(Avion avion)
        {
            if (ModelState.IsValid)
            {
                db.Entry(avion).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.AerolineaId = new SelectList(db.Aerolineas, "Id", "Nombre", avion.AerolineaId);
            return View(avion);
        }

        public ActionResult Delete(int id)
        {
            Avion avion = db.Aviones.Find(id);
            return View(avion);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Avion avion = db.Aviones.Find(id);
            db.Aviones.Remove(avion);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}